package com.frinder.official.akka.routing;

import akka.actor.ActorRef;
import akka.routing.BroadcastPool;
import com.frinder.official.spring.MyBaseActor;
import com.frinder.official.spring.SpringExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import static com.frinder.official.akka.routing.PayloadActor.Payload;

/**
 * Created by frinder on 2017/9/29.
 */
@Component
@Scope("prototype")
public class BroadcastRouter extends MyBaseActor {

    final int routees = 4;

    @Autowired
    SpringExtension springExtension;

    ActorRef router;

    @Override
    public void preStart() throws Exception {
        super.preStart();
        router = getContext().actorOf(
                new BroadcastPool(routees).props(springExtension.props("payloadActor")),
                "broadcast-router"
        );
    }

    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .match(Payload.class, payload -> router.tell(payload, getSender()))
                .build();
    }
}
